//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System.Collections.Generic;
using System.Expressions;
using System.Query;

namespace Mindscape.BackgroundMotion.Core.Utilities
{
  public static class LinqContainsPredicateBuilder
  {
    /// <summary>
    /// Builds the specified collection.
    /// </summary>
    /// <param name="collection">The collection.</param>
    /// <param name="targetProperty">The target property.</param>
    /// <returns></returns>
    public static Expression<Func<T, bool>> Build<T, S>(ICollection<S> collection, string targetProperty)
    {
      Invariant.ArgumentNotEmpty(collection, "collection");
      Invariant.ArgumentNotEmpty(targetProperty, "targetProperty");

      Expression completeExpression = null;
      ParameterExpression parameterExpression = Expression.Parameter(typeof(T), "t");

      foreach (S item in collection)
      {
        Expression nextExpression = Expression.EQ
          (
          Expression.Property(parameterExpression, typeof(T).GetProperty(targetProperty)),
          Expression.Constant(item)
          );

        completeExpression = (completeExpression != null)
          ? Expression.OrElse(completeExpression, nextExpression)
          : nextExpression;
      }

      return (Expression<Func<T, bool>>)QueryExpression.Lambda(completeExpression, parameterExpression);
    }
  }
}